package com.ymatou.iapi.synctrade.service;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.collections.CollectionUtils;
import org.json.JSONObject;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.shop2cn.iapi.sqsynctrade.paremeter.es.OrderES;
import com.shop2cn.iapi.sqsynctrade.paremeter.mongo.details.Fund;
import com.shop2cn.iapi.sqsynctrade.paremeter.mongo.details.PrepaidCardRefund;
import com.shop2cn.iapi.sqsynctrade.paremeter.mongo.details.Product;
import com.shop2cn.iapi.sqsynctrade.paremeter.mongo.details.ProductProxyPo;
import com.shop2cn.iapi.sqsynctrade.paremeter.mongo.details.ProductSubCode;
import com.shop2cn.iapi.sqsynctrade.paremeter.mongo.details.Refund;
import com.shop2cn.iapi.sqsynctrade.paremeter.mongo.details.StatusLog;
import com.shop2cn.iapi.sqsynctrade.paremeter.mongo.details.SubProduct;
import com.ymatou.iapi.optrade.parameter.req.RiskControlNotifyReq;
import com.ymatou.iapi.optrade.parameter.utill.Utils;
import com.ymatou.iapi.optrade.service.RiskControlNotifyCall;
import com.ymatou.iapi.synctrade.parameter.SyncByCommandReq;
import com.ymatou.iapi.synctrade.parameter.TradingSyncCmdEnum;
import com.ymatou.iapi.synctrade.parameter.mongo.HunterIndex;
import com.ymatou.iapi.synctrade.parameter.mongo.Order;
import com.ymatou.iapi.synctrade.parameter.mongo.ProxyIndex;
import com.ymatou.iapi.synctrade.parameter.mongo.SellerIndex;
import com.ymatou.iapi.synctrade.parameter.mongo.UserIndex;
import com.ymatou.iapi.synctrade.parameter.mongo.details.PickupStore;
import com.ymt.base.YmatouEasyCall;
import com.ymt.core.tool.Logger;
import com.ymttest.business.service.YMTTrading.TradingCallService;
import com.ymttest.business.service.shenqi.GodmchManageCallService;
import com.ymttest.business.service.shenqi.SqTradingProductService;
import com.ymttest.database.mongo.HunterIndexQueryWapper;
import com.ymttest.database.mongo.OrderQueryWapper;
import com.ymttest.database.mongo.ProxyOrderIndexQueryWapper;
import com.ymttest.database.mongo.SellerIndexQueryWapper;
import com.ymttest.database.mongo.SyncCommandWapper;
import com.ymttest.database.mongo.UserIndexQueryWapper;
import com.ymttest.database.sharding.db.sharding.model.OrderPo;
import com.ymttest.database.sharding.db.sharding.model.ShenqiProxyChainPo;
import com.ymttest.database.sharding.db.sharding.model.ShenqiSellerProfitPo;
import com.ymttest.database.sharding.db.sqlwapper.OrderShardingWapper;
import com.ymttest.database.sharding.db.sqlwapper.OrderWapper;
import com.ymttest.utils.DataUtil;
import com.ymttest.utils.TestDataManager;
import com.ymttest.utils.YMTDateUtil;

public class TradingSyncService {

	private static OrderShardingWapper orderShardingWapper = new OrderShardingWapper();
	
	/**
	 * 根据订单查询同步到mongo 数据结果
	 * 
	 * @param orderId
	 * */
	public static boolean getSyncResult(long orderId) {

		return getSyncResult(orderId, null);
	}
	
	/**
	 * 根据订单查询同步到mongo 数据结果
	 * 
	 * @param orderId
	 * */
	@SuppressWarnings("rawtypes")
	public static boolean getSyncResult(long orderId, String command) {

		Long time1 = System.currentTimeMillis();

		try {

			Map result = new HashMap();

			long count = 0;

			while (count < 150) {

				if (null == command)
					result = new SyncCommandWapper("Cmd")
							.getTradingSyncCommand(orderId);
				else
					result = new SyncCommandWapper("Cmd")
							.getTradingSyncCommand(orderId, command);

				if (result == null) {

					count++;
					continue;
				}

				if ((Integer) result.get("ost") >= 1
						&& (Integer) result.get("sst") >= 1
						&& (Integer) result.get("ust") >= 1
						&& ((Integer) result.get("est") >= 1 || (Integer) result
								.get("est") == -2)) {

					// Thread.sleep(75000);
					Long time2 = System.currentTimeMillis();

					Logger.debug("同步到mongo及ES用时:" + (time2 - time1) / 1000
							+ "s");

					return true;
				}

				count++;
			}
			Long time3 = System.currentTimeMillis();
			if (result == null) {
				Logger.debug("同步到mongo及ES用时:" + (time3 - time1) / 1000
						+ "s, mongo 结果为null，同步失败");
				return false;
			}

		} catch (Exception e) {

			e.printStackTrace();
		}
		Long time4 = System.currentTimeMillis();
		Logger.debug("同步到mongo及ES用时:" + (time4 - time1) / 1000 + "s, 同步失败");
		return false;
	}

	/**
	 * 调用接口查询同步到es order 数据
	 * 
	 * @param orderId
	 * */
	public static OrderES getOrderFromES(long orderId) {

		YmatouEasyCall OrderFromMongoCall = new YmatouEasyCall("", "POST",
				"JSON");
		OrderES order = new OrderES();
		String orderJson = "{\"id\":" + orderId + "}";
		OrderFromMongoCall
				.setUrl("http://es.trading.iapi.ymatou.com/api/OrderSync/GetOrder");
		OrderFromMongoCall.setData(orderJson);
		try {
			OrderFromMongoCall.callService();
			JSONObject jsonObject = new JSONObject(
					OrderFromMongoCall.getReturnData()).getJSONObject("data");

			// order = (OrderES) FormatUtil.GSONToObject(
			// jsonObject.optString("order"), OrderES.class);

			Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss")
					.disableHtmlEscaping().create();
			order = (OrderES) gson.fromJson(jsonObject.optString("order"),
					OrderES.class);

			Logger.debug("returndata:" + OrderFromMongoCall.getReturnData());

		} catch (Exception e) {

			e.printStackTrace();
		}

		return order;
	}
	
	/**
	 * 调用接口查询同步到es order 数据
	 * 
	 * @param orderId
	 * */
	public static OrderES getOrderFromSqES(long orderId) {

		YmatouEasyCall OrderFromMongoCall = new YmatouEasyCall("", "POST",
				"JSON");
		OrderES order = new OrderES();
		String orderJson = "{\"id\":" + orderId + "}";
		OrderFromMongoCall
				.setUrl("http://sqes.trading.iapi.shop2cn.com/api/OrderSync/GetOrder");
		OrderFromMongoCall.setData(orderJson);
		try {
			OrderFromMongoCall.callService();
			JSONObject jsonObject = new JSONObject(
					OrderFromMongoCall.getReturnData()).getJSONObject("data");

			// order = (OrderES) FormatUtil.GSONToObject(
			// jsonObject.optString("order"), OrderES.class);

			Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss")
					.disableHtmlEscaping().create();
			order = (OrderES) gson.fromJson(jsonObject.optString("order"),
					OrderES.class);

			Logger.debug("returndata:" + OrderFromMongoCall.getReturnData());

		} catch (Exception e) {

			e.printStackTrace();
		}

		return order;
	}

	/**
	 * 调用接口查询mongo 数据 order 数据
	 * 
	 * @param orderId
	 * */
	public static Order getOrderFromMongo(long orderId) {

		return new OrderQueryWapper().findById(orderId);

	}

	/**
	 * 调用接口查询mongo 数据 SellerIndex 数据
	 * 
	 * @param orderId
	 * */
	public static SellerIndex getSellerIndexFromMongo(long orderId,
			long sellerId) {

		return new SellerIndexQueryWapper().findByOrderId(orderId, sellerId);
	}

	/**
	 * 调用接口查询mongo 数据 SellerIndex 数据
	 * 
	 * @param orderId
	 * @param userId
	 * */
	public static UserIndex getUserIndexFromMongo(long orderId, long userId) {
		return new UserIndexQueryWapper().findById(orderId, userId);
	}

	/**
	 * 调用接口查询mongo 数据 ProxyIndex 数据
	 * 
	 * @param orderId
	 * @param userId
	 * */
	public static ProxyIndex getPorxyIndexFromMongo(long orderId, long sellerId) {
		return new ProxyOrderIndexQueryWapper().findById(orderId, sellerId);
	}

	/**
	 * 调用接口查询mongo 数据HunterIndex 数据
	 * 
	 * @param orderId
	 * @param userId
	 * */
	public static HunterIndex getHunterIndexFromMongo(long orderId,
			long hunterId) {
		return new HunterIndexQueryWapper().findById(orderId, hunterId);
	}

	/**
	 * 码头保存发货物流单号
	 * 
	 * @param orderId
	 * @param sellerId
	 * */
	public static String saveDeliverSummary(long orderId, long sellerId) {

		String billCode = "Auto" + TestDataManager.getRandomNum(5);

		try {
			YmatouEasyCall SaveDeliverSummaryCall = new YmatouEasyCall("",
					"POST", "JSON");
			StringBuffer saveDeliverSummaryString = new StringBuffer();
			saveDeliverSummaryString
					.append("{\"SaveDeliverSummaryInfos\":[{\"BillCode\":\"");
			saveDeliverSummaryString.append(billCode);
			saveDeliverSummaryString.append("\",");
			saveDeliverSummaryString
					.append("\"CanReDelivery\":0,\"CatalogStatus\":\"7\",\"DeliverType\":2,\"ExpressCode\":\"xlobo\",\"InnerExpressCode\":\"\",\"IsChinaDeliver\":true,");
			saveDeliverSummaryString.append("\"OrderId\":");
			saveDeliverSummaryString.append(orderId);
			saveDeliverSummaryString.append(",");
			saveDeliverSummaryString
					.append("\"Provider\":\"洋码头官方合作物流（xLobo贝海国际速递）\",");
			saveDeliverSummaryString.append("\"SellerId\":");
			saveDeliverSummaryString.append(sellerId);
			saveDeliverSummaryString.append(",");
			saveDeliverSummaryString.append("\"Weight\":10}]}");
			SaveDeliverSummaryCall
			// .setUrl("http://orderdelivery.iapi.ymatou.com/api/Deliver/SaveDeliverSummary");
					.setUrl("http://api.seller.ymatou.com/api/Deliver/SaveDeliverSummary");

			SaveDeliverSummaryCall.setData(saveDeliverSummaryString.toString());

			Logger.comment("发货保存运单号");
			SaveDeliverSummaryCall.callService();

			if (new JSONObject(SaveDeliverSummaryCall.getReturnData())
					.getInt("Code") == 200)
				return billCode;

		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;

	}

	/**
	 * 修改运单号
	 * 
	 * @param orderId
	 *            订单号
	 * @param sellerId
	 *            买手id
	 * @param newBillCode
	 *            新物流单号
	 * @param oldBillCode
	 *            旧物流单号
	 * @param ymtExpressCode
	 *            物流公司代码
	 * */
	public static void modifyDeliverBillCode(long orderId, long sellerId,
			String newBillCode, String oldBillCode, String ymtExpressCode) {
		try {
			YmatouEasyCall SaveDeliverSummaryCall = new YmatouEasyCall("",
					"POST", "JSON");
			StringBuffer saveDeliverSummaryString = new StringBuffer();

			saveDeliverSummaryString.append("{\"billNo\":\"");
			saveDeliverSummaryString.append(newBillCode);
			saveDeliverSummaryString.append("\",");
			saveDeliverSummaryString.append("\"oldBillNo\":\"");
			saveDeliverSummaryString.append(oldBillCode);
			saveDeliverSummaryString.append("\",");
			saveDeliverSummaryString.append("\"ymtExpressCode\":\"");
			saveDeliverSummaryString.append(ymtExpressCode);
			saveDeliverSummaryString.append("\",");
			saveDeliverSummaryString.append("\"SellerId\":");
			saveDeliverSummaryString.append(sellerId);
			saveDeliverSummaryString.append(",");
			saveDeliverSummaryString.append("\"OrderId\":");
			saveDeliverSummaryString.append(orderId);
			saveDeliverSummaryString.append("}");

			SaveDeliverSummaryCall
					.setUrl("http://delivery.iapi.ymatou.com/delivery/modifyDeliveryBillNo");

			SaveDeliverSummaryCall.setData(saveDeliverSummaryString.toString());
			Logger.comment("发货处理");
			SaveDeliverSummaryCall.callService();

			if (new JSONObject(SaveDeliverSummaryCall.getReturnData())
					.getInt("Code") == 200)
				;

		} catch (Exception e) {

			e.printStackTrace();
		}
	}
	
	/**
	 * 
	 * @param orderId
	 * @param userId
	 * @param sellerId
	 */
	public static void verify(long orderId, long userId, long sellerId) {
		verify(orderId, userId, sellerId, 0);
	}

	public static void verify(long orderId, long userId, long sellerId,
			long hunterId) {
		Order orderMongo = getOrderFromMongo(orderId);

		UserIndex userIndexBean = getUserIndexFromMongo(orderId, userId);

		SellerIndex sellerIndex = getSellerIndexFromMongo(orderId, sellerId);

		HunterIndex hunterIndex = getHunterIndexFromMongo(orderId, hunterId);

		OrderES orderEsBean = getOrderFromES(orderId);

		try {
			
			// 查询mysql 订单相关的全量表数据
			Order expectOrderSql = orderShardingWapper
					.selectCommandByOrder(orderId, userId, false);
			
			OrderPo memberOrder = orderShardingWapper.selectOrderbyLinkPayanliOrderId(expectOrderSql.getMainOrderId());
			
			if (null != memberOrder) {
				
				expectOrderSql.setMemberOrderPaidAmount(memberOrder.getPayableAmount());
			}
			
			//普通订单不同步此字段, MAIN_ORDER/HUNTER_ID指令和二次确认订单会同步
			orderMongo.setSupportOfflinePay(Utils.falseIfNull(orderMongo
					.getSupportOfflinePay()));
			orderMongo.setOfflinePayFlag(Utils.falseIfNull(orderMongo
					.getOfflinePayFlag()));
			
			Logger.comment(String
					.format("校验Mongo库order表数据 orderId %s", orderId));

			DataUtil.verifyObject2(expectOrderSql, orderMongo,
					"校验mysql 数据跟mongo 数据比对 Order");

			List<Product> expectProList = expectOrderSql.getProducts();

			List<Product> actualProList = orderMongo.getProducts();

			for (int i = 0; i < expectProList.size(); i++) {

				Logger.comment(String.format("校验 orderId %s 下 第 %s 个商品",
						orderId, i + 1));

				Product expect = expectProList.get(i);
				
				if (!expect.getAuthenticateFlag())
					expect.setAuthenticateFlag(null);
				
				// 二次确认订单会同步AuthenticateFlag
				if (Utils
						.falseIfNull(expectOrderSql.getSecondConfirmTime() != null)) {

					expect.setAuthenticateFlag(false);
				}

				if (!expect.getInAuthenticateCenter())
					expect.setInAuthenticateCenter(null);
				
				Product actual = actualProList.get(i);

				DataUtil.verifyObject2(expect, actual,
						"校验mysql 数据跟mongo 数据比对 Order.Product");
			}

			List<Refund> expectRefundList = expectOrderSql.getRefunds();
			List<Refund> actualRefundList = orderMongo.getRefunds();

			if (!CollectionUtils.isEmpty(expectRefundList)) {

				for (int i = 0; i < expectRefundList.size(); i++) {

					Logger.comment(String.format("校验 orderId %s 下 第 %s 个退款单",
							orderId, i + 1));

					Refund expect = expectRefundList.get(i);
					Refund actual = actualRefundList.get(i);

					DataUtil.verifyObject2(expect, actual,
							"校验mysql 数据跟mongo 数据比对 Order.Refund");
				}
			}

			List<StatusLog> expectStatusLogList = expectOrderSql.getStatusLog();
			List<StatusLog> actualStatusLogList = orderMongo.getStatusLog();

			if (!CollectionUtils.isEmpty(expectStatusLogList)) {
				for (int i = 0; i < expectStatusLogList.size(); i++) {

					Logger.comment(String.format(
							"校验 orderId %s 下 第 %s 个StatusLog", orderId, i + 1));

					StatusLog expect = expectStatusLogList.get(i);
					StatusLog actual = actualStatusLogList.get(i);

					DataUtil.verifyObject2(expect, actual,
							"校验mysql 数据跟mongo 数据比对 Order.StatusLog");

				}
			}

			List<SubProduct> expectSubProductList = expectOrderSql
					.getSubProducts();
			List<SubProduct> actualSubProductList = orderMongo.getSubProducts();

			if (!CollectionUtils.isEmpty(expectSubProductList)) {

				for (int i = 0; i < expectSubProductList.size(); i++) {

					Logger.comment(String.format("校验 orderId %s 下 第 %s 个组合商品",
							orderId, i + 1));

					SubProduct expect = expectSubProductList.get(i);
					SubProduct actual = actualSubProductList.get(i);

					DataUtil.verifyObject2(expect, actual,
							"校验mysql 数据跟mongo 数据比对 Order.SubProduct");
				}
			}

			List<String> expectPrepaidCardNoList = expectOrderSql
					.getPrepaidCardNos();
			List<String> actualPrepaidCardNoList = orderMongo
					.getPrepaidCardNos();

			if (!CollectionUtils.isEmpty(expectPrepaidCardNoList)) {

				for (int i = 0; i < expectPrepaidCardNoList.size(); i++) {

					Logger.comment(String.format(
							"校验 orderId %s 下 第 %s 个PrepaidCardNo", orderId,
							i + 1));

					String expect = expectPrepaidCardNoList.get(i);
					String actual = actualPrepaidCardNoList.get(i);

					DataUtil.verifyObject2(expect, actual,
							"校验mysql 数据跟mongo 数据比对 Order.PrepaidCardNo");

				}
			}
			List<PrepaidCardRefund> expectPrepaidCardRefundList = expectOrderSql
					.getPrepaidCardRefunds();
			List<PrepaidCardRefund> actualPrepaidCardRefundList = orderMongo
					.getPrepaidCardRefunds();

			if (!CollectionUtils.isEmpty(expectPrepaidCardRefundList)) {

				for (int i = 0; i < expectPrepaidCardRefundList.size(); i++) {

					Logger.comment(String.format("校验 orderId %s 下 第 %s 个预付卡退款",
							orderId, i + 1));

					PrepaidCardRefund expect = expectPrepaidCardRefundList
							.get(i);
					PrepaidCardRefund actual = actualPrepaidCardRefundList
							.get(i);

					DataUtil.verifyObject2(expect, actual,
							"校验mysql 数据跟mongo 数据比对 Order.PrepaidCardRefund");

				}
			}

			Logger.comment(String.format("校验 orderId %s 支付信息", orderId));

			Fund expectFund = expectOrderSql.getFund();

			setDefaultValue(expectFund);

			DataUtil.verifyObject2(expectFund, orderMongo.getFund(),
					"校验mysql 数据跟mongo 数据比对 Order.Fund");

			Logger.comment(String.format("校验 orderId %s 物流信息", orderId));

			if (expectOrderSql.getDelivery() != null) {
				
				Logger.verifyEquals(true, DataUtil.verifyListStringExceptSort(
						expectOrderSql.getDelivery().getBillCode(), orderMongo
								.getDelivery().getBillCode()),
						"校验mysql 数据跟mongo 数据比对 Order.Delivery.billCode");

				if (CollectionUtils.isEmpty(expectOrderSql.getDelivery()
						.getBizType())) {

					expectOrderSql.getDelivery().setBizType(null);
				}

				Logger.verifyEquals(expectOrderSql.getDelivery().getBizType(),
						orderMongo.getDelivery().getBizType(),
						"校验mysql 数据跟mongo 数据比对 Order.Delivery.BizType");
			}

			else {

				if (orderMongo.getDelivery() != null) {

					DataUtil.verifyObject2(null, orderMongo.getDelivery()
							.getBillCode(),
							"校验mysql 数据跟mongo 数据比对 Order.Delivery");
				}

				else {
					DataUtil.verifyObject2(null, orderMongo.getDelivery(),
							"校验mysql 数据跟mongo 数据比对 Order.Delivery");
				}
			}

			verifyMongoIndex(expectOrderSql, sellerIndex, userIndexBean);

			if (hunterId != 0) {
				verifyMongoHunterIndex(expectOrderSql, hunterIndex);
			}

			verifyES(expectOrderSql, sellerIndex, orderEsBean);

		} catch (Exception e) {

			e.printStackTrace();
			// Logger.debug(e.getMessage());
		}
	}

	public static void verifyDGSQ(long orderId, long userId) {
		Order orderMongo = getOrderFromMongo(orderId);

		UserIndex userIndexBean = getUserIndexFromMongo(orderId, userId);

		OrderES orderEsBean = getOrderFromSqES(orderId);

		try {

			// 查询mysql 订单相关的全量表数据
			Order expectOrderSql = orderShardingWapper.selectCommandByOrder(
					orderId, userId, true);
			
			orderMongo.setSupportOfflinePay(Utils.falseIfNull(orderMongo
					.getSupportOfflinePay()));
			orderMongo.setOfflinePayFlag(Utils.falseIfNull(orderMongo
					.getOfflinePayFlag()));
			
			orderMongo.setCurrency(orderMongo.getCurrency() == null ? "CNY"
					: orderMongo.getCurrency());
			
			orderMongo.setLuxury(Utils.falseIfNull(orderMongo.getLuxury()));
			orderMongo.setLogistic(Utils.falseIfNull(orderMongo.getLogistic()));

			Logger.comment(String
					.format("校验Mongo库order表数据 orderId %s", orderId));

			DataUtil.verifyObject2(expectOrderSql, orderMongo,
					"校验mysql 数据跟mongo 数据比对 Order");
			
			List<ProductSubCode> expectProductSubCodeList = expectOrderSql.getProductSubCodes();
			List<ProductSubCode> actualProductSubCodeList = orderMongo.getProductSubCodes();

			if (!CollectionUtils.isEmpty(expectProductSubCodeList)) {

				for (int i = 0; i < expectProductSubCodeList.size(); i++) {

					Logger.comment(String.format("校验 orderId %s 下 第 %s 个子码",
							orderId, i + 1));

					ProductSubCode expect = expectProductSubCodeList.get(i);
					ProductSubCode actual = actualProductSubCodeList.get(i);

					DataUtil.verifyObject2(expect, actual,
							"校验mysql 数据跟mongo 数据比对 Order.ProductSubCode");
				}
			}

			List<Product> expectProList = expectOrderSql.getProducts();
			List<Product> actualProList = orderMongo.getProducts();
			
//			actualProList = actualProList
//					.stream()
//					.sorted(Comparator.comparing(Product::getItemId).reversed())
//					.collect(Collectors.toList());

			for (int i = 0; i < expectProList.size(); i++) {

				Logger.comment(String.format("校验 orderId %s 下 第 %s 个商品",
						orderId, i + 1));

				Product expect = expectProList.get(i);
				
				// taxRate特殊处理，保留6位小数
				expect.setTaxRate(expect.getTaxRate().multiply(new BigDecimal("1000000")));
				
				// customsTaxRate特殊处理，保留6位小数
				expect.setCustomsTaxRate(expect.getCustomsTaxRate().multiply(new BigDecimal("1000000")));
				
				if (!CollectionUtils.isEmpty(expectProductSubCodeList))
					expect.setvStockCount(0);
				
				Product actual = actualProList.get(i);
				
				actual.setvStockCount(Utils.zeroIfNull(actual.getvStockCount()));

				if (expectOrderSql.getIsFullPaidOrder())
					expect.setWaitInStock(null);
				
				DataUtil.verifyObject2(expect, actual,
						"校验mysql 数据跟mongo 数据比对 Order.Product");
			}

			List<Refund> expectRefundList = expectOrderSql.getRefunds();
			List<Refund> actualRefundList = orderMongo.getRefunds();

			if (!CollectionUtils.isEmpty(expectRefundList)) {

				for (int i = 0; i < expectRefundList.size(); i++) {

					Logger.comment(String.format("校验 orderId %s 下 第 %s 个退款单",
							orderId, i + 1));

					Refund expect = expectRefundList.get(i);
					Refund actual = actualRefundList.get(i);

					DataUtil.verifyObject2(expect, actual,
							"校验mysql 数据跟mongo 数据比对 Order.Refund");
				}
			}

			List<StatusLog> expectStatusLogList = expectOrderSql.getStatusLog();
			List<StatusLog> actualStatusLogList = orderMongo.getStatusLog();

			if (!CollectionUtils.isEmpty(expectStatusLogList)) {
				for (int i = 0; i < expectStatusLogList.size(); i++) {

					Logger.comment(String.format(
							"校验 orderId %s 下 第 %s 个StatusLog", orderId, i + 1));

					StatusLog expect = expectStatusLogList.get(i);
					StatusLog actual = actualStatusLogList.get(i);

					DataUtil.verifyObject2(expect, actual,
							"校验mysql 数据跟mongo 数据比对 Order.StatusLog");
				}
			}

			List<SubProduct> expectSubProductList = expectOrderSql
					.getSubProducts();
			List<SubProduct> actualSubProductList = orderMongo.getSubProducts();
			
			if (null != actualSubProductList)
				actualSubProductList = actualSubProductList
						.stream()
						.sorted(Comparator
								.comparing(SubProduct::getSubCatalogId))
						.collect(Collectors.toList());
			
			if (!CollectionUtils.isEmpty(expectSubProductList)) {

				for (int i = 0; i < expectSubProductList.size(); i++) {

					Logger.comment(String.format("校验 orderId %s 下 第 %s 个组合商品",
							orderId, i + 1));

					SubProduct expect = expectSubProductList.get(i);
					SubProduct actual = actualSubProductList.get(i);
					
					// customsTaxRate特殊处理，保留6位小数
					expect.setCustomsTaxRate(expect.getCustomsTaxRate().multiply(new BigDecimal("1000000")));

					DataUtil.verifyObject2(expect, actual,
							"校验mysql 数据跟mongo 数据比对 Order.SubProduct");
				}
			}

			List<String> expectPrepaidCardNoList = expectOrderSql
					.getPrepaidCardNos();
			List<String> actualPrepaidCardNoList = orderMongo
					.getPrepaidCardNos();

			if (!CollectionUtils.isEmpty(expectPrepaidCardNoList)) {

				for (int i = 0; i < expectPrepaidCardNoList.size(); i++) {

					Logger.comment(String.format(
							"校验 orderId %s 下 第 %s 个PrepaidCardNo", orderId,
							i + 1));

					String expect = expectPrepaidCardNoList.get(i);
					String actual = actualPrepaidCardNoList.get(i);

					DataUtil.verifyObject2(expect, actual,
							"校验mysql 数据跟mongo 数据比对 Order.PrepaidCardNo");
				}
			}

			List<PrepaidCardRefund> expectPrepaidCardRefundList = expectOrderSql
					.getPrepaidCardRefunds();
			List<PrepaidCardRefund> actualPrepaidCardRefundList = orderMongo
					.getPrepaidCardRefunds();

			if (!CollectionUtils.isEmpty(expectPrepaidCardRefundList)) {

				for (int i = 0; i < expectPrepaidCardRefundList.size(); i++) {

					Logger.comment(String.format("校验 orderId %s 下 第 %s 个预付卡退款",
							orderId, i + 1));

					PrepaidCardRefund expect = expectPrepaidCardRefundList
							.get(i);
					PrepaidCardRefund actual = actualPrepaidCardRefundList
							.get(i);

					DataUtil.verifyObject2(expect, actual,
							"校验mysql 数据跟mongo 数据比对 Order.PrepaidCardRefund");
				}
			}

			Logger.comment(String.format("校验 orderId %s 支付信息", orderId));

			Fund expectFund = expectOrderSql.getFund();

			setDefaultValue(expectFund);

			DataUtil.verifyObject2(expectFund, orderMongo.getFund(),
					"校验mysql 数据跟mongo 数据比对 Order.Fund");

			Logger.comment(String.format("校验 orderId %s 物流信息", orderId));

			if (expectOrderSql.getDelivery() != null) {

				DataUtil.verifyListStringExceptSort(expectOrderSql
						.getDelivery().getBillCode(), orderMongo.getDelivery()
						.getBillCode());
				Logger.verifyEquals(true, DataUtil.verifyListStringExceptSort(
						expectOrderSql.getDelivery().getBillCode(), orderMongo
								.getDelivery().getBillCode()),
						"校验mysql 数据跟mongo 数据比对 Order.Delivery.billCode");

				if (CollectionUtils.isEmpty(expectOrderSql.getDelivery()
						.getBizType())) {

					expectOrderSql.getDelivery().setBizType(null);
				}

				Logger.verifyEquals(expectOrderSql.getDelivery().getBizType(),
						orderMongo.getDelivery().getBizType(),
						"校验mysql 数据跟mongo 数据比对 Order.Delivery.BizType");
			} else {

				if (orderMongo.getDelivery() != null) {

					DataUtil.verifyObject2(new OrderWapper()
							.selectDeliveryCodeByOrderId(orderId), orderMongo
							.getDelivery().getBillCode() == null ? new ArrayList<String>()
							: orderMongo.getDelivery().getBillCode(),
							"校验mysql 数据跟mongo 数据比对 Order.Delivery");
				} else {
					
					DataUtil.verifyObject2(null, orderMongo.getDelivery(),
							"校验mysql 数据跟mongo 数据比对 Order.Delivery");
				}
			}
			
			PickupStore expectPickupStore = expectOrderSql
					.getPickupStore();
			PickupStore actualPrepaidPickupStore = orderMongo
					.getPickupStore();

			if (null != expectPickupStore) {

				Logger.comment(String.format("校验 orderId %s 下自提信息", orderId));
				DataUtil.verifyObject2(expectPickupStore,
						actualPrepaidPickupStore,
						"校验mysql 数据跟mongo 数据比对 Order.PickupStore");
			}
			
			List<ShenqiSellerProfitPo> shenqiSellerProfitList = orderShardingWapper
					.selectSellerProfitbyOrderId(orderId);
			
			ShenqiSellerProfitPo negativeProfitPo = shenqiSellerProfitList.stream().filter(
					shenqiSellerProfitPo -> shenqiSellerProfitPo.getProfit()
							.compareTo(BigDecimal.ZERO) == -1).findAny().orElse(null);
			
			boolean sellerNegativeProfit = negativeProfitPo == null ? false : true;

			if (expectOrderSql.getSellerId().longValue() == expectOrderSql
					.getGoodsOwnerId().longValue()) {

				ProxyIndex expectProxyOrderIndex = new ProxyIndex();
				ProxyIndex proxyOrderIndex = null;

				ShenqiSellerProfitPo shenqiSellerProfitPo = orderShardingWapper
						.selectSellerProfitbyOrderIdAndSellerId(orderId,
								expectOrderSql.getGoodsOwnerId());
				
				expectProxyOrderIndex.setOrderId(orderId);
				expectProxyOrderIndex.setSellerId(expectOrderSql.getSellerId());
				expectProxyOrderIndex.setChildSellerId(0L);
				expectProxyOrderIndex.setUserId(userId);
				expectProxyOrderIndex.setMainOrderId(expectOrderSql
						.getMainOrderId());
				expectProxyOrderIndex.setTradingStatus(expectOrderSql
						.getTradingStatus());

				expectProxyOrderIndex.setSellerRole(shenqiSellerProfitPo.getSellerRole());
				expectProxyOrderIndex.setIncome(shenqiSellerProfitPo.getProfit());
				
				expectProxyOrderIndex.setDeliveryType(expectOrderSql
						.getShenqiLogisticsType());
				expectProxyOrderIndex.setCurrency(expectOrderSql.getCurrency());
				expectProxyOrderIndex.setShenqiPaymentRmbAmount(expectOrderSql.getShenqiPaymentRmbAmount());
				expectProxyOrderIndex.setHidden(getHidden(expectOrderSql.getBizType(),
						expectOrderSql.getBizStatus()));
				expectProxyOrderIndex.setSellerNegativeProfit(sellerNegativeProfit);
				expectProxyOrderIndex.setPickupInStores(expectOrderSql.getPickupInStores());
				expectProxyOrderIndex.setWarehouseId(expectOrderSql.getWarehouseId());
				expectProxyOrderIndex.setDistributorId(expectOrderSql.getDistributorId());
				
				expectProxyOrderIndex
						.setWaitInStock(expectOrderSql.getWaitInStock());
				expectProxyOrderIndex.setInStockTime(expectOrderSql.getInStockTime());
				expectProxyOrderIndex.setSellerMemo(shenqiSellerProfitPo.getSellerMemo());
				expectProxyOrderIndex.setPayableAmount(expectOrderSql.getPayableAmount());
				expectProxyOrderIndex.setPlatSource(expectOrderSql.getPlatSource());
				expectProxyOrderIndex.setLiveOrder(expectOrderSql.getLiveOrder());
				
				if (null != expectOrderSql.getRefunds()) {
					
					// 去除失败的退款单
					List<Refund> refundListExcludeFailed = expectOrderSql
							.getRefunds()
							.stream()
							.filter(refund -> refund.getRefundStatus() == 1
									|| refund.getRefundStatus() == 10
									|| refund.getRefundStatus() == -2 ).collect(Collectors.toList());
					
					if (refundListExcludeFailed.size() > 0) {
						
						expectProxyOrderIndex.setHasRefund(true);
						expectProxyOrderIndex.setLastRefundTime(expectOrderSql
								.getRefunds()
								.get(expectOrderSql.getRefunds().size() - 1)
								.getRefundTime());
					} else {
						
						expectProxyOrderIndex.setHasRefund(null);
						expectProxyOrderIndex.setLastRefundTime(null);
					}
				} else {
					
					expectProxyOrderIndex.setHasRefund(null);
					expectProxyOrderIndex.setLastRefundTime(null);
				}
				
				proxyOrderIndex = getPorxyIndexFromMongo(orderId,
						expectOrderSql.getSellerId());
				verifyMongoProxyIndex(expectProxyOrderIndex, proxyOrderIndex);

			} else {

				// 代理链按照catalogId倒序排序
				List<ProductProxyPo> expectProductProxies = expectOrderSql
						.getProductProxies()
						.stream()
						.sorted(Comparator.comparing(
								ProductProxyPo::getCatalogId).reversed())
						.collect(Collectors.toList());
				List<ProductProxyPo> actualProductProxies = orderMongo
						.getProductProxies();

				if (!CollectionUtils.isEmpty(expectProductProxies)) {

					ProxyIndex proxyOrderIndex = new ProxyIndex();
					boolean isInherited = GodmchManageCallService.isInheritedAgent(expectOrderSql.getSellerId());

					for (int i = 0; i < expectProductProxies.size(); i++) {

						Logger.comment(String.format(
								"校验 orderId %s 下 第 %s 个代理链", orderId, i + 1));

						ProductProxyPo expect = expectProductProxies.get(i);
						ProductProxyPo actual = actualProductProxies.get(i);

						DataUtil.verifyObject2(expect, actual,
								"校验mysql 数据跟mongo 数据比对 Order.ProductProxy");
					}

					// 所有规格的代理链条都是一样的，所以取其中一个规格获取所需的seller数量
					List<ShenqiProxyChainPo> shenqiProxyChain = isInherited ? SqTradingProductService
							.getInheritedProxyChainInfo(expectOrderSql
									.getProducts().get(0).getCataId(),
									expectOrderSql.getSellerId())
							: SqTradingProductService
									.getProxyChainInfoList(expectOrderSql
											.getProducts().get(0).getCataId(), expectOrderSql.getSellerId());

					// 客服的收入
					BigDecimal serviceIncome = BigDecimal.ZERO;
					
					int i = 1;

					for (ShenqiProxyChainPo chainPo : shenqiProxyChain) {

						ShenqiSellerProfitPo shenqiSellerProfitPo = orderShardingWapper
								.selectSellerProfitbyOrderIdAndSellerId(orderId,
										chainPo.getSellerId());
						
						ProxyIndex expectProxyOrderIndex = new ProxyIndex();
						
						expectProxyOrderIndex.setOrderId(orderId);
						expectProxyOrderIndex
								.setSellerId(chainPo.getSellerId());
						expectProxyOrderIndex.setChildSellerId(chainPo
								.getChildSellerId());
						expectProxyOrderIndex.setUserId(userId);
						expectProxyOrderIndex.setMainOrderId(expectOrderSql
								.getMainOrderId());
						expectProxyOrderIndex.setTradingStatus(expectOrderSql
								.getTradingStatus());
						expectProxyOrderIndex.setDeliveryType(expectOrderSql
								.getShenqiLogisticsType());
						expectProxyOrderIndex.setCurrency(expectOrderSql.getCurrency());
						expectProxyOrderIndex.setShenqiPaymentRmbAmount(expectOrderSql.getShenqiPaymentRmbAmount());
						expectProxyOrderIndex.setHidden(getHidden(expectOrderSql.getBizType(),
								expectOrderSql.getBizStatus()));
						expectProxyOrderIndex.setPickupInStores(expectOrderSql.getPickupInStores());
						expectProxyOrderIndex.setWarehouseId(expectOrderSql.getWarehouseId());
						expectProxyOrderIndex.setDistributorId(expectOrderSql.getDistributorId());
						expectProxyOrderIndex.setInStockTime(expectOrderSql.getInStockTime());
						
						expectProxyOrderIndex.setSubDistributionProfit(shenqiSellerProfitPo.getSubDistributionProfit());
						
						expectProxyOrderIndex.setWaitInStock(expectOrderSql
								.getWaitInStock());
						
						expectProxyOrderIndex.setSellerRole(shenqiSellerProfitPo.getSellerRole());
						expectProxyOrderIndex
								.setIncome(shenqiSellerProfitPo.getProfit());
						
						if (null != expectOrderSql.getRefunds()) {
							
							// 去除失败的退款单
							List<Refund> refundListExcludeFailed = expectOrderSql
									.getRefunds()
									.stream()
									.filter(refund -> refund.getRefundStatus() == 1
											|| refund.getRefundStatus() == 10
											|| refund.getRefundStatus() == -2 ).collect(Collectors.toList());
							
							if (refundListExcludeFailed.size() > 0) {
								
								expectProxyOrderIndex.setHasRefund(true);
								expectProxyOrderIndex.setLastRefundTime(expectOrderSql
										.getRefunds()
										.get(expectOrderSql.getRefunds().size() - 1)
										.getRefundTime());
							} else {
								
								expectProxyOrderIndex.setHasRefund(null);
								expectProxyOrderIndex.setLastRefundTime(null);
							}
						} else {
							
							expectProxyOrderIndex.setHasRefund(null);
							expectProxyOrderIndex.setLastRefundTime(null);
						}

						serviceIncome = expectProxyOrderIndex.getIncome();
						
						expectProxyOrderIndex.setSellerNegativeProfit(sellerNegativeProfit);
						expectProxyOrderIndex.setSellerMemo(shenqiSellerProfitPo.getSellerMemo());
						expectProxyOrderIndex.setPayableAmount(expectOrderSql.getPayableAmount());
						
						expectProxyOrderIndex.setPlatSource(expectOrderSql.getPlatSource());
						expectProxyOrderIndex.setLiveOrder(expectOrderSql.getLiveOrder());
						
						proxyOrderIndex = getPorxyIndexFromMongo(orderId,
								chainPo.getSellerId());
						verifyMongoProxyIndex(expectProxyOrderIndex,
								proxyOrderIndex);
						
						i = i + 1;
					}

					if (expectOrderSql.getSalesman() != 0) {

						ShenqiSellerProfitPo shenqiSellerProfitPo = orderShardingWapper
								.selectSellerProfitbyOrderIdAndSellerId(
										orderId, expectOrderSql.getSalesman());
						
						ProxyIndex expectProxyOrderIndex = new ProxyIndex();
						
						expectProxyOrderIndex.setOrderId(orderId);
						expectProxyOrderIndex.setSellerId(expectOrderSql
								.getSalesman());
						expectProxyOrderIndex.setIncome(serviceIncome);
						expectProxyOrderIndex.setChildSellerId(0L);
						expectProxyOrderIndex.setUserId(userId);
						expectProxyOrderIndex.setMainOrderId(expectOrderSql
								.getMainOrderId());
						expectProxyOrderIndex.setTradingStatus(expectOrderSql
								.getTradingStatus());
						expectProxyOrderIndex.setSellerRole(5);
						expectProxyOrderIndex.setDeliveryType(expectOrderSql
								.getShenqiLogisticsType());
						expectProxyOrderIndex.setCurrency(expectOrderSql.getCurrency());
						expectProxyOrderIndex.setShenqiPaymentRmbAmount(expectOrderSql.getShenqiPaymentRmbAmount());
						expectProxyOrderIndex.setHidden(getHidden(expectOrderSql.getBizType(),
								expectOrderSql.getBizStatus()));
						expectProxyOrderIndex.setSellerNegativeProfit(sellerNegativeProfit);
						expectProxyOrderIndex.setPickupInStores(expectOrderSql.getPickupInStores());
						expectProxyOrderIndex.setWarehouseId(expectOrderSql.getWarehouseId());
						expectProxyOrderIndex.setDistributorId(expectOrderSql.getDistributorId());
						expectProxyOrderIndex.setInStockTime(expectOrderSql.getInStockTime());
						expectProxyOrderIndex.setPayableAmount(expectOrderSql.getPayableAmount());
						
						expectProxyOrderIndex.setWaitInStock(expectOrderSql
								.getWaitInStock());
						
						expectProxyOrderIndex.setPlatSource(expectOrderSql
								.getPlatSource());
						expectProxyOrderIndex.setLiveOrder(expectOrderSql
								.getLiveOrder());
						
						if (null != expectOrderSql.getRefunds()) {
							
							// 去除失败的退款单
							List<Refund> refundListExcludeFailed = expectOrderSql
									.getRefunds()
									.stream()
									.filter(refund -> refund.getRefundStatus() == 1
											|| refund.getRefundStatus() == 10
											|| refund.getRefundStatus() == -2 ).collect(Collectors.toList());
							
							if (refundListExcludeFailed.size() > 0) {
								
								expectProxyOrderIndex.setHasRefund(true);
								expectProxyOrderIndex.setLastRefundTime(expectOrderSql
										.getRefunds()
										.get(expectOrderSql.getRefunds().size() - 1)
										.getRefundTime());
							} else {
								
								expectProxyOrderIndex.setHasRefund(null);
								expectProxyOrderIndex.setLastRefundTime(null);
							}
						} else {
							
							expectProxyOrderIndex.setHasRefund(null);
							expectProxyOrderIndex.setLastRefundTime(null);
						}
						
						expectProxyOrderIndex.setSellerMemo(shenqiSellerProfitPo.getSellerMemo());

						proxyOrderIndex = getPorxyIndexFromMongo(orderId,
								expectOrderSql.getSalesman());
						verifyMongoProxyIndex(expectProxyOrderIndex,
								proxyOrderIndex);
					}
				}
			}
			
			verifyUserIndex(expectOrderSql, userIndexBean);

			verifyDGSQES(expectOrderSql, orderEsBean);

		} catch (Exception e) {

			e.printStackTrace();
			// Logger.debug(e.getMessage());
		}
	}

	/**
	 * 校验Mongo Index索引数据
	 * 
	 */
	private static void verifyMongoIndex(Order expectOrderSql,
			SellerIndex sellerIndex, UserIndex userIndexBean) {

		Logger.comment("校验Mongo库UserIndex表数据");

		DataUtil.verify(expectOrderSql.getPayDeductAmount(),
				userIndexBean.getPayDeductAmount(), "验证payDeductAmount");

		DataUtil.verify(expectOrderSql.getId(), userIndexBean.getId(),
				"验证orderId");

		if (expectOrderSql.getEarnestAmount().compareTo(BigDecimal.ZERO) == 1)
			DataUtil.verify(true, userIndexBean.isBookingOrder(),
					"验证bookingOrder");
		else
			DataUtil.verify(false, userIndexBean.isBookingOrder(),
					"验证bookingOrder");

		DataUtil.verify(expectOrderSql.isCanConfirm(),
				userIndexBean.isCanConfirm(), "验证canConfirm");

		DataUtil.verify(expectOrderSql.getUserId(), userIndexBean.getUserId(),
				"验证userId");
		DataUtil.verify(expectOrderSql.getMainOrderId(),
				userIndexBean.getMainOrderId(), "验证mainOrderId");
		DataUtil.verify(expectOrderSql.getTradingStatus(),
				userIndexBean.getTradingStatus(), "验证tradingStatus");
		DataUtil.verifyDecimalEquals(expectOrderSql.getHunterId(),
				userIndexBean.getHunterId(), "验证HunterId");
		DataUtil.verifyDecimalEquals(expectOrderSql.getHunterOrderType(),
				userIndexBean.getHunterOrderType(), "验证HunterOrderType");
		DataUtil.verifyDateEquals(true,Utils.calcTimeSpanSec(expectOrderSql.getAddTime(),
				userIndexBean.getAddTime()) < 5, "验证addTime");

		DataUtil.verifyDateEquals(expectOrderSql.getPaidTime(),
				userIndexBean.getPaidTime(), "验证数据库PaidTime");
		DataUtil.verifyDateEquals(expectOrderSql.getReceiveTime(),
				userIndexBean.getReceiveTime(), "验证receiveTime");

		Logger.verifyEquals(expectOrderSql.getSellerId(),
				userIndexBean.getSellerId(), "验证数据库SellerId");

		Logger.verifyEquals(expectOrderSql.getTradingId(),
				userIndexBean.getTradingId(), "验证数据库TradingId");
		Logger.verifyEquals(expectOrderSql.isDeleted(),
				userIndexBean.getDeleted(), "验证数据库deleted");
		
		DataUtil.verifyDateEquals(expectOrderSql.getOrderType(),
				userIndexBean.getOrderType(), "验证orderType");
		
		DataUtil.verifyDateEquals(expectOrderSql.getPayChannel(),
				userIndexBean.getPayChannel(), "验证payChannel");
		DataUtil.verifyDateEquals(expectOrderSql.getBizType(),
				userIndexBean.getBizType(), "验证bizType");
		
		DataUtil.verifyEquals(expectOrderSql.getLuxury(),
				userIndexBean.getLuxury(), "验证luxury");

		Logger.comment("校验Mongo库SellerIndex表数据");

		DataUtil.verify(expectOrderSql.getId(), sellerIndex.getId(),
				"验证iOrderId");
		DataUtil.verify(expectOrderSql.getUserId(), sellerIndex.getUserId(),
				"验证iUserId");
		DataUtil.verify(expectOrderSql.getMainOrderId(),
				sellerIndex.getMainOrderId(), "验证iMainOrderId");
		DataUtil.verify(expectOrderSql.getSellerId(),
				sellerIndex.getSellerId(), "验证sellerId");
		DataUtil.verify(expectOrderSql.getTradingStatus(),
				sellerIndex.getTradingStatus(), "验证tradingStatus");
		DataUtil.verifyDateEquals(expectOrderSql.getAddTime(),
				sellerIndex.getAddTime(), "验证addTime");
		DataUtil.verifyDateEquals(expectOrderSql.getCancelTime(),
				sellerIndex.getCancelTime(), "验证cancelTime");
		DataUtil.verifyDateEquals(expectOrderSql.getPaidTime(),
				sellerIndex.getPaidTime(), "验证paidTime");
		DataUtil.verifyDateEquals(expectOrderSql.getAcceptTime(),
				sellerIndex.getAcceptTime(), "验证acceptTime");
		DataUtil.verifyDateEquals(expectOrderSql.getDeliveryTime(),
				sellerIndex.getDeliveryTime(), "验证deliveryTime");
		
		DataUtil.verifyDateEquals(expectOrderSql.isActualRebate(),
				sellerIndex.isActualRebate(), "验证actualRebate");
		
		DataUtil.verifyDateEquals(expectOrderSql.getOuterPromotionId(),
				sellerIndex.getOuterPromotionId(), "验证OuterPromotionId");

		if (expectOrderSql.getEarnestAmount().compareTo(BigDecimal.ZERO) == 1)
			DataUtil.verify(true, sellerIndex.isBookingOrder(),
					"验证bookingOrder");
		else
			DataUtil.verify(false, sellerIndex.isBookingOrder(),
					"验证bookingOrder");

		DataUtil.verifyDateEquals(expectOrderSql.getDeliverEndTime(),
				sellerIndex.getDeliverEndTime(), "验证deliverEndTime");
		DataUtil.verifyDateEquals(expectOrderSql.getEarnestPaidTime(),
				sellerIndex.getEarnestPaidTime(), "验证earnestPaidTime");

		DataUtil.verify(expectOrderSql.isLocalDelivery(),
				sellerIndex.isLocalDelivery(), "验证LocalDelivery");

		int autoCancelSecond = expectOrderSql.getAutoCancelHour()
				.multiply(new BigDecimal(60)).multiply(new BigDecimal(60))
				.intValue();

		Calendar c = Calendar.getInstance();
		c.setTime(expectOrderSql.getAddTime());
		c.add(Calendar.SECOND, autoCancelSecond);

		Logger.verifyEquals(
				true,
				Utils.calcTimeSpanSec(sellerIndex.getAutoCancelTime(),
						c.getTime()) < 5, "验证数据库autoCancelTime跟计算的时间差为5秒钟内");

		// 物流类型
		DataUtil.verify(expectOrderSql.getDeliveryType(),
				sellerIndex.getDeliveryType(), "验证DeliveryType");

		Logger.verifyEquals(expectOrderSql.isXlobo(), sellerIndex.isXlobo(),
				"验证数据库Xlobo");
		
//		List<String> billCodes = new OrderWapper()
//				.selectDeliveryCodeByOrderIdWithDeleted(expectOrderSql.getId());
//		
//		// sellerIndex的物流单号为大写
//		Logger.verifyEquals(true, DataUtil.verifyListStringExceptSort(
//				billCodes.size() == 0 ? null : billCodes.stream()
//						.map(billCode -> billCode.toUpperCase())
//						.collect(Collectors.toList()),
//				sellerIndex.getBillCode()), "验证数据库BillCode");
		
		// sellerIndex的物流单号为大写
		if (expectOrderSql.getDelivery() == null)
			Logger.verifyEquals(null, sellerIndex.getBillCode(),
					"验证数据库BillCode");
		else
			Logger.verifyEquals(true, DataUtil.verifyListStringExceptSort(
					expectOrderSql.getDelivery().getBillCode().size() == 0 ? null
							: expectOrderSql.getDelivery().getBillCode().stream()
									.map(billCode -> billCode.toUpperCase())
									.collect(Collectors.toList()), sellerIndex
							.getBillCode()), "验证数据库BillCode");
		

		DataUtil.verify(expectOrderSql.isPreSale(), sellerIndex.isPreSale(),
				"验证bPreSale");
		DataUtil.verify(expectOrderSql.getRemarkLevel() == null ? 0
				: expectOrderSql.getRemarkLevel(),
				sellerIndex.getRemarkLevel(), "验证iRemarkLevel");

		// 用户应付
		BigDecimal cardAmount = BigDecimal.ZERO;

		if (expectOrderSql.getFund() != null) {
			cardAmount = cardAmount.add(expectOrderSql.getFund()
					.getPrepaidCard());
		}

		DataUtil.verify(
				expectOrderSql.getPayableAmount().add(
						expectOrderSql.getFund().getPrepaidCard()),
				sellerIndex.getUserPay(), "验证userPay");

		// 成交额(TotalPrice + Freight)
		DataUtil.verify(
				expectOrderSql.getFreight().add(expectOrderSql.getTotalPrice()),
				sellerIndex.getSales(), "验证sales");

		// 平台优惠券
		DataUtil.verify(expectOrderSql.getYmtCouponAmount(),
				sellerIndex.getYmtCouponAmount(), "验证YmtCouponAmount");

		BigDecimal usePay = BigDecimal.ZERO;
		// 直播成交额
		BigDecimal sales = BigDecimal.ZERO;
		BigDecimal ymtCoupon = BigDecimal.ZERO;
		Integer dlvType = null;

		for (Product prd : expectOrderSql.getProducts()) {

			if (prd.getSalesType() == null || prd.getSalesType() == 2) {

				sales = sales.add(
						Utils.zeroIfNull(prd.getPrdPrice()).multiply(
								new BigDecimal(prd.getPrdCount()))).add(
						Utils.zeroIfNull(prd.getPrdFreight()));
				ymtCoupon = ymtCoupon.add(Utils.zeroIfNull(prd
						.getPrdYmtCoupon()));
				usePay = usePay
						.add(Utils
								.zeroIfNull(prd.getPrdPrice())
								.multiply(new BigDecimal(prd.getPrdCount()))
								.add(Utils.zeroIfNull(prd.getPrdFreight()))
								.add(Utils.zeroIfNull(prd.getPrdDiscount()))
								.subtract(
										Utils.zeroIfNull(prd
												.getPrdPromotionAmount()))
								.subtract(
										Utils.zeroIfNull(prd
												.getPrdSellerCoupon()))
								.subtract(
										Utils.zeroIfNull(prd.getPrdYmtCoupon())));

			}
			if (dlvType == null) {
				dlvType = prd.getDeliveryType();
			}
		}

		// 直播成交额
		DataUtil.verifyDecimalEquals(sales, sellerIndex.getSalesLive(),
				"验证salesLive");
		// 直播用户应付
		DataUtil.verifyDecimalEquals(usePay, sellerIndex.getUserPayLive(),
				"验证userPayLive");
		// 直播平台优惠券
		DataUtil.verifyDecimalEquals(ymtCoupon,
				sellerIndex.getYmtCouponAmountLive(), "验证ymtCouponAmountLive");

		DataUtil.verify(
				CollectionUtils.isEmpty(expectOrderSql.getRefunds()) ? false
						: true, sellerIndex.isRefunded(), "验证refunded");

		BigDecimal refundCash = BigDecimal.ZERO;
		BigDecimal refundCoupon = BigDecimal.ZERO;

		if (expectOrderSql.getFund() != null) {
			refundCash = expectOrderSql.getFund().getRefundCash();
			refundCoupon = expectOrderSql.getFund().getRefundCoupon();
		}

		DataUtil.verifyDecimalEquals(refundCash, sellerIndex.getRefundCash(),
				"验证refundCash");

		DataUtil.verifyDecimalEquals(refundCoupon,
				sellerIndex.getRefundCoupon(), "验证refundCoupon");

		// 买家登录Id
		DataUtil.verify(expectOrderSql.getUserLogin(),
				sellerIndex.getUserLogin(), "验证sBuyerLoginId");

		DataUtil.verify(expectOrderSql.getReceiver(),
				sellerIndex.getReceiver(), "验证Receiver");

		DataUtil.verify(
				getHidden(expectOrderSql.getBizType(),
						expectOrderSql.getBizStatus()),
				sellerIndex.getHidden(), "验证hidden");
		
		DataUtil.verify(expectOrderSql.getAuthenticateFlag(), sellerIndex.getAuthenticateFlag(),
				"验证AuthenticateFlag");
		
		DataUtil.verify(expectOrderSql.getOfficialLogistics(), sellerIndex.getOfficialLogistics(),
				"验证OfficialLogistics");
		
		DataUtil.verify(expectOrderSql.getLogisticsAging(), sellerIndex.getLogisticsAging(),
				"验证LogisticsAging");
	}

	/**
	 * 校验Mongo UserIndex索引数据
	 * 
	 */
	private static void verifyUserIndex(Order expectOrderSql,
			UserIndex userIndexBean) {

		Logger.comment("校验Mongo库UserIndex表数据");

		DataUtil.verify(expectOrderSql.getPayDeductAmount(),
				userIndexBean.getPayDeductAmount(), "验证payDeductAmount");

		DataUtil.verify(expectOrderSql.getId(), userIndexBean.getId(),
				"验证orderId");

		if (expectOrderSql.getEarnestAmount().compareTo(BigDecimal.ZERO) == 1)
			DataUtil.verify(true, userIndexBean.isBookingOrder(),
					"验证bookingOrder");
		else
			DataUtil.verify(false, userIndexBean.isBookingOrder(),
					"验证bookingOrder");

		DataUtil.verify(expectOrderSql.isCanConfirm(),
				userIndexBean.isCanConfirm(), "验证canConfirm");

		DataUtil.verify(expectOrderSql.getUserId(), userIndexBean.getUserId(),
				"验证userId");
		DataUtil.verify(expectOrderSql.getMainOrderId(),
				userIndexBean.getMainOrderId(), "验证mainOrderId");
		DataUtil.verify(expectOrderSql.getTradingStatus(),
				userIndexBean.getTradingStatus(), "验证tradingStatus");
		DataUtil.verifyDecimalEquals(expectOrderSql.getHunterId(),
				userIndexBean.getHunterId(), "验证HunterId");
		DataUtil.verifyDecimalEquals(expectOrderSql.getHunterOrderType(),
				userIndexBean.getHunterOrderType(), "验证HunterOrderType");
		DataUtil.verifyDateEquals(expectOrderSql.getAddTime(),
				userIndexBean.getAddTime(), "验证addTime");

		DataUtil.verifyDateEquals(expectOrderSql.getPaidTime(),
				userIndexBean.getPaidTime(), "验证数据库PaidTime");
		DataUtil.verifyDateEquals(expectOrderSql.getReceiveTime(),
				userIndexBean.getReceiveTime(), "验证receiveTime");

		Logger.verifyEquals(expectOrderSql.getSellerId(),
				userIndexBean.getSellerId(), "验证数据库SellerId");

		Logger.verifyEquals(expectOrderSql.getTradingId(),
				userIndexBean.getTradingId(), "验证数据库TradingId");
		Logger.verifyEquals(expectOrderSql.isDeleted(),
				userIndexBean.getDeleted(), "验证数据库deleted");
		
		Logger.verifyEquals(expectOrderSql.getPayChannel(),
				userIndexBean.getPayChannel(), "验证payChannel");
		Logger.verifyEquals(expectOrderSql.getBizType(),
				userIndexBean.getBizType(), "验证bizType");
		
		Logger.verifyEquals(expectOrderSql.getPickupInStores(),
				userIndexBean.getPickupInStores(), "验证pickupInStores");
		DataUtil.verifyDateEquals(expectOrderSql.getEntryTime(),
				userIndexBean.getEntryTime(), "验证entryTime");
		DataUtil.verifyDateEquals(expectOrderSql.getShenqiPaymentRmbAmount(),
				userIndexBean.getShenqiRmbAmount(), "验证shenqiRmbAmount");
	}

	/**
	 * 校验Mongo HunterOrderIndex索引数据
	 * 
	 */
	private static void verifyMongoHunterIndex(Order expectOrderSql,
			HunterIndex hunterIndex) {
		Logger.comment("校验Mongo库HunterOrderIndex表数据");

		DataUtil.verify(expectOrderSql.getId(), hunterIndex.getId(),
				"验证orderId");
		DataUtil.verify(expectOrderSql.getTradingStatus(),
				hunterIndex.getTradingStatus(), "验证tradingStatus");
		DataUtil.verifyDateEquals(expectOrderSql.getHunterId(),
				hunterIndex.getHunterId(), "验证HunterId");
		Logger.verifyEquals(expectOrderSql.getSellerId(),
				hunterIndex.getSellerId(), "验证数据库SellerId");
		DataUtil.verify(expectOrderSql.getMainOrderId(),
				hunterIndex.getMainOrderId(), "验证mainOrderId");
		DataUtil.verifyDateEquals(expectOrderSql.getPaidTime(),
				hunterIndex.getPaidTime(), "验证数据库PaidTime");
		DataUtil.verifyDateEquals(expectOrderSql.getAddTime(),
				hunterIndex.getAddTime(), "验证addTime");
		DataUtil.verifyDateEquals(expectOrderSql.getDeliveryTime(),
				hunterIndex.getDeliveryTime(), "验证deliveryTime");
		DataUtil.verify(expectOrderSql.getUserId(), hunterIndex.getUserId(),
				"验证userId");
		DataUtil.verify(expectOrderSql.getUserLogin(),
				hunterIndex.getUserLoginId(), "验证sBuyerLoginId");
		DataUtil.verifyDateEquals(expectOrderSql.getHunterOrderType(),
				hunterIndex.getHunterOrderType(), "验证HunterOrderType");
	}

	/**
	 * 校验Mongo proxyOrderIndex索引数据
	 * 
	 */
	private static void verifyMongoProxyIndex(ProxyIndex expectProxyOrderIndex,
			ProxyIndex proxyIndex) {
		Logger.comment("校验Mongo库ProxyOrderIndex表数据:"
				+ expectProxyOrderIndex.getSellerId());

		DataUtil.verify(expectProxyOrderIndex.getOrderId(),
				proxyIndex.getOrderId(), "验证orderId");
		DataUtil.verify(expectProxyOrderIndex.getTradingStatus(),
				proxyIndex.getTradingStatus(), "验证tradingStatus");
		Logger.verifyEquals(expectProxyOrderIndex.getSellerId(),
				proxyIndex.getSellerId(), "验证数据库SellerId");
		DataUtil.verify(expectProxyOrderIndex.getMainOrderId(),
				proxyIndex.getMainOrderId(), "验证mainOrderId");
		DataUtil.verify(expectProxyOrderIndex.getUserId(),
				proxyIndex.getUserId(), "验证userId");
		DataUtil.verify(expectProxyOrderIndex.getIncome(),
				proxyIndex.getIncome(), "验证income");
		DataUtil.verify(expectProxyOrderIndex.getSellerRole(),
				proxyIndex.getSellerRole(), "验证sellerRole");
		DataUtil.verify(expectProxyOrderIndex.getChildSellerId(),
				proxyIndex.getChildSellerId(), "验证childSellerId");
		DataUtil.verify(expectProxyOrderIndex.getDeliveryType(),
				proxyIndex.getDeliveryType(), "验证deliveryType");
		DataUtil.verify(expectProxyOrderIndex.getCurrency(), proxyIndex
				.getCurrency() == null ? "CNY" : proxyIndex.getCurrency(),
				"验证currency");
		DataUtil.verify(expectProxyOrderIndex.getHidden(),
				proxyIndex.getHidden(), "验证hidden");
		DataUtil.verify(expectProxyOrderIndex.getPickupInStores(),
				proxyIndex.getPickupInStores(), "验证pickupInStores");
		DataUtil.verify(expectProxyOrderIndex.getWarehouseId(),
				proxyIndex.getWarehouseId(), "验证warehouseId");
		DataUtil.verify(expectProxyOrderIndex.getDistributorId(),
				proxyIndex.getDistributorId(), "验证distributorId");
		
		DataUtil.verify(expectProxyOrderIndex.getSubDistributionProfit(),
				proxyIndex.getSubDistributionProfit(), "验证subDistributionProfit");
		
		DataUtil.verify(expectProxyOrderIndex.getWaitInStock(),
				Utils.falseIfNull(proxyIndex.getWaitInStock()), "验证waitInStock");
		DataUtil.verify(expectProxyOrderIndex.getInStockTime(),
				proxyIndex.getInStockTime(), "验证inStockTime");
		
		DataUtil.verify(expectProxyOrderIndex.getHasRefund(),
				proxyIndex.getHasRefund(), "验证hasRefund");
		DataUtil.verify(expectProxyOrderIndex.getLastRefundTime(),
				proxyIndex.getLastRefundTime(), "验证lastRefundTime");
		DataUtil.verify(expectProxyOrderIndex.getSellerMemo(),
				proxyIndex.getSellerMemo(), "验证sellerMemo");
		DataUtil.verifyDecimalEquals(expectProxyOrderIndex.getPayableAmount(),
				proxyIndex.getPayableAmount(), "验证PayableAmount");
	}

	/**
	 * 校验ES索引数据
	 * 
	 */
	private static void verifyES(Order expectOrderSql, SellerIndex sellerIndex,
			OrderES orderEsBean) {

		Logger.comment("校验ES索引数据");

		try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {

			e.printStackTrace();
		}

		DataUtil.verify(expectOrderSql.getId(), orderEsBean.getId(), "验证id");
		DataUtil.verify(expectOrderSql.getMainOrderId(), orderEsBean.getMain(),
				"验证main");

		// 商品名称集合
		List<String> titles = new ArrayList<String>();

		for (Product pro : expectOrderSql.getProducts()) {
			titles.add(pro.getTitle());
		}

		DataUtil.verify(titles, Arrays.asList(orderEsBean.getTitle()),
				"验证title");

		for (int i = 0; i < expectOrderSql.getProducts().size(); i++) {
			Logger.comment("校验ES索引第" + (i + 1) + "商品数据");
			DataUtil.verify(expectOrderSql.getProducts().get(i).getProductId(),
					orderEsBean.getPrd().get(i).getPrdId(), "验证prdId");
			DataUtil.verify(expectOrderSql.getProducts().get(i).getTitle(),
					orderEsBean.getPrd().get(i).getTitle(), "验证title");
			DataUtil.verify(expectOrderSql.getProducts().get(i).getPrdCount(),
					orderEsBean.getPrd().get(i).getCount(), "验证count");
			DataUtil.verify(expectOrderSql.getProducts().get(i).getSku(),
					orderEsBean.getPrd().get(i).getSku(), "验证sku");
			DataUtil.verify(expectOrderSql.getProducts().get(i).getGraphicProduct(),
					orderEsBean.getPrd().get(i).getGraphicPrd(), "验证graphicProduct");
		}
		Logger.comment("校验ES索引商品数据结束");

		DataUtil.verify(expectOrderSql.getUserId(), orderEsBean.getUser(),
				"验证user");

		DataUtil.verify(expectOrderSql.getUserLogin(),
				orderEsBean.getUserLgi(), "验证userLgi");
		DataUtil.verifyDecimalEquals(expectOrderSql.getHunterId(),
				orderEsBean.getHunterId(), "验证hunterId");
		DataUtil.verifyDecimalEquals(expectOrderSql.getHunterOrderType(),
				orderEsBean.getHOrdTp(), "验证hunterOrderType");
		DataUtil.verify(expectOrderSql.getReceiver(), orderEsBean.getRecv(),
				"验证recv");

		DataUtil.verify(Utils.decryptAES(expectOrderSql.getUphone()),
				orderEsBean.getPhone(), "验证phone");
		DataUtil.verify(expectOrderSql.getSellerId(), orderEsBean.getSeller(),
				"验证seller");
		DataUtil.verify(expectOrderSql.getTradingStatus(), orderEsBean.getSt(),
				"验证st");

		// DataUtil.verifyDateEquals(expected, actual, desc);
		DataUtil.verifyDateEquals(expectOrderSql.getAddTime(),
				orderEsBean.getAddTm(), "验证addTm");
		DataUtil.verifyDateEquals(expectOrderSql.getAcceptTime(),
				orderEsBean.getAcpTm(), "验证acpTm");
		DataUtil.verifyDateEquals(expectOrderSql.getPaidTime(),
				orderEsBean.getPaidTm(), "验证paidTm");
		DataUtil.verify(expectOrderSql.getSellerCouponCode(),
				orderEsBean.getSellerCopCod(), "验证sellerCopCod");

//		DataUtil.verify(expectOrderSql.getPayableAmount().add(expectOrderSql.getFund().getPrepaidCard()),
//				orderEsBean.getUserPay(), "验证userPay");
		DataUtil.verify(expectOrderSql.getPayableAmount(),
				orderEsBean.getUserPay(), "验证userPay");

		DataUtil.verify(sellerIndex.getSales(), orderEsBean.getSales(),
				"验证sales");

		DataUtil.verify(expectOrderSql.getYmtCouponCode(),
				orderEsBean.getYmtCopCod(), "验证ymtCopCod");

		DataUtil.verify(expectOrderSql.getYmtCouponAmount(),
				orderEsBean.getYmtCop(), "验证ymtCop");

		DataUtil.verify(
				sellerIndex.getBillCode(),

				orderEsBean.getDlvCode() == null ? null : Arrays
						.asList(orderEsBean.getDlvCode()).toString()
						.toUpperCase(), "验证dlvCode");

		DataUtil.verify(sellerIndex.getDeliveryType(), orderEsBean.getDlvTp(),
				"验证dlvTp");
		DataUtil.verifyDateEquals(sellerIndex.getDeliveryTime(),
				orderEsBean.getDlvTm(), "验证dlvTm");

		DataUtil.verifyDateEquals(sellerIndex.isLocalDelivery(),
				orderEsBean.getLocDlv(), "验证locDlv");
		DataUtil.verifyDateEquals(expectOrderSql.getReceiveTime(),
				orderEsBean.getRecvTm(), "验证recvTm");
		DataUtil.verifyDateEquals(expectOrderSql.isPreSale(),
				orderEsBean.getPreSale(), "验证preSale");

		DataUtil.verifyDateEquals(CollectionUtils.isEmpty(expectOrderSql
				.getRefunds()) ? null : true, orderEsBean.getRfded(), "验证rfded");
		DataUtil.verifyDateEquals(expectOrderSql.getRemarkLevel(),
				orderEsBean.getRmklvl(), "验证rmklvl");

		DataUtil.verifyDateEquals(expectOrderSql.isDeleted(),
				orderEsBean.getDel(), "验证del");

		BigDecimal refundCash = BigDecimal.ZERO;
		BigDecimal refundCoupon = BigDecimal.ZERO;

		if (expectOrderSql.getFund() != null) {
			refundCash = expectOrderSql.getFund().getRefundCash();
			refundCoupon = expectOrderSql.getFund().getRefundCoupon();
		}

		DataUtil.verify(refundCash, orderEsBean.getRfdCsh(), "验证rfdCsh");

		DataUtil.verify(refundCoupon, orderEsBean.getRfdCop(), "验证rfdCop");

		DataUtil.verifyDateEquals(expectOrderSql.getBizId(),
				orderEsBean.getBizId(), "验证bizId");
		DataUtil.verifyDateEquals(expectOrderSql.getBizType(),
				orderEsBean.getBizTp(), "验证bizType");
		DataUtil.verifyDateEquals(expectOrderSql.getBizStatus(),
				orderEsBean.getBizSt(), "验证bizStatus");

		DataUtil.verifyDecimalEquals(sellerIndex.getUserPayLive(),
				orderEsBean.getLvPay(), "验证lvPay");

		DataUtil.verifyDateEquals(sellerIndex.getEarnestPaidTime(),
				orderEsBean.getEtPdTm(), "验证earnestPaidTime");
		DataUtil.verify(sellerIndex.isBookingOrder(), orderEsBean.getBkOrder(),
				"验证BookingOrder");
		DataUtil.verifyDateEquals(expectOrderSql.getPaymentEndTime(),
				orderEsBean.getpEdTm(), "验证paymentEndTime");
		DataUtil.verifyDateEquals(expectOrderSql.getPreDiscount(),
				orderEsBean.getPreDisc(), "验证preDisc");
		
		DataUtil.verifyDateEquals(expectOrderSql.getOrderType(),
				orderEsBean.getOt(), "验证orderType");
		DataUtil.verifyDateEquals(expectOrderSql.isActualRebate(),
				orderEsBean.getActRb(), "验证actualRebate");
		
		Logger.verifyEquals(expectOrderSql.getOuterPromotionId(),
				orderEsBean.getOuterPromId(), "验证OuterPromId");
		
		Logger.verifyEquals(expectOrderSql.getAuthenticateFlag(),
				orderEsBean.getAuctFlag(), "验证AuctFlag");
		
		Logger.verifyEquals(expectOrderSql.getLogisticsAging(),
				orderEsBean.getLgAg(), "验证LgAg");
		Logger.verifyEquals(expectOrderSql.getOfficialLogistics(),
				orderEsBean.getOfficLg(), "验证OfficLg");
		Logger.verifyEquals(expectOrderSql.getSupplementDomestic(),
				orderEsBean.getSuppDst(), "验证SuppDst");
	}

	/**
	 * 校验ES索引数据
	 * @throws Exception 
	 * 
	 */
	private static void verifyDGSQES(Order expectOrderSql, OrderES orderEsBean) throws Exception {

		Logger.comment("校验ES索引数据");

		try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {

			e.printStackTrace();
		}

		DataUtil.verify(expectOrderSql.getId(), orderEsBean.getId(), "验证id");
		DataUtil.verify(expectOrderSql.getMainOrderId(), orderEsBean.getMain(),
				"验证main");
		
		List<Product> actualProList = expectOrderSql.getProducts();
		
		actualProList = actualProList
				.stream()
				.sorted(Comparator.comparing(Product::getCataId).reversed())
				.collect(Collectors.toList());

		// 商品名称集合
		List<String> titles = new ArrayList<String>();

		for (Product pro : actualProList) {
			titles.add(pro.getTitle());
		}

		DataUtil.verify(titles, Arrays.asList(orderEsBean.getTitle()),
				"验证title");
		
		for (int i = 0; i < actualProList.size(); i++) {
			Logger.comment("校验ES索引第" + (i + 1) + "商品数据");

			Product product = actualProList.get(i);

			DataUtil.verify(product.getProductId(), orderEsBean.getPrd().get(i)
					.getPrdId(), "验证prdId");
			DataUtil.verify(product.getTitle(), orderEsBean.getPrd().get(i)
					.getTitle(), "验证title");
			DataUtil.verify(product.getPrdCount(), orderEsBean.getPrd().get(i)
					.getCount(), "验证count");
			DataUtil.verify(Utils.zeroIfNull(product.getvStockCount()),
					orderEsBean.getPrd().get(i).getvStockCount(),
					"验证vStockCount");
			DataUtil.verify(product.getCataId(), orderEsBean.getPrd().get(i)
					.getCatId(), "验证catId");
						
			DataUtil.verify(
					Utils.falseIfNull(product.getWaitInStock()),
					Utils.falseIfNull(orderEsBean.getPrd().get(i).getWtInSto()),
					"验证WtInSto");
			
			DataUtil.verify(product.getRefundCount(), orderEsBean.getPrd().get(i)
					.getRfdCnt(), "验证RfdCnt");
			DataUtil.verify(product.getPrdRefundStatus(), orderEsBean.getPrd().get(i)
					.getPrdRfdSt(), "验证PrdRfdSt");
			DataUtil.verify(product.getPrdRefundNo(), orderEsBean.getPrd().get(i)
					.getPrdRfdNo(), "验证PrdRfdNo");

			if (expectOrderSql.getSellerId().longValue() != expectOrderSql
					.getGoodsOwnerId().longValue()) {

				String goodsOwnerCatId = expectOrderSql
						.getProductProxies()
						.stream()
						.filter(productProxy -> productProxy.getSellerId() == expectOrderSql
								.getGoodsOwnerId()
								&& productProxy.getCatalogId()
										.equalsIgnoreCase(product.getCataId()))
						.collect(Collectors.toList()).get(0)
						.getProxyCatalogId();

				DataUtil.verify(goodsOwnerCatId, orderEsBean.getPrd().get(i)
						.getGoodsOwnerCatId(), "验证goodsOwnerCatId");
			} else {

				DataUtil.verify(product.getCataId(), orderEsBean.getPrd()
						.get(i).getGoodsOwnerCatId(), "验证goodsOwnerCatId");
			}
			
			// sku同步偏慢，重试获取3次
			if (null != expectOrderSql.getProducts().get(i).getSku()) {
				
				int count = 0;
				
				while (null == orderEsBean.getPrd().get(i).getSku()) {
					
					Thread.sleep(count * 1000);
					
					if (count == 3)
						break;
					
					orderEsBean = getOrderFromSqES(orderEsBean.getId());
					count ++;
				}
				
				DataUtil.verify(expectOrderSql.getProducts().get(i).getSku(),
						orderEsBean.getPrd().get(i).getSku(), "验证sku");
			} else
				DataUtil.verify(expectOrderSql.getProducts().get(i).getSku(),
						orderEsBean.getPrd().get(i).getSku(), "验证sku");
		}

		Logger.comment("校验ES索引商品数据结束");

		DataUtil.verify(expectOrderSql.getUserId(), orderEsBean.getUser(),
				"验证user");

		DataUtil.verify(expectOrderSql.getUserLogin(),
				orderEsBean.getUserLgi(), "验证userLgi");
		DataUtil.verify(expectOrderSql.getReceiver(), orderEsBean.getRecv(),
				"验证recv");

		DataUtil.verify(Utils.decryptAES(expectOrderSql.getUphone()),
				orderEsBean.getPhone(), "验证phone");
		DataUtil.verify(expectOrderSql.getSellerId(), orderEsBean.getSeller(),
				"验证seller");
		DataUtil.verify(expectOrderSql.getTradingStatus(), orderEsBean.getSt(),
				"验证st");

		Logger.verifyEquals(
				true,
				Utils.calcTimeSpanSec(expectOrderSql.getAddTime(), YMTDateUtil
						.getDate(orderEsBean.getAddTm(), YMTDateUtil.YMDHMS)) < 5,
				"验证数据库AddTime跟系统当前时间差为5秒钟内");
		DataUtil.verifyDateEquals(expectOrderSql.getAcceptTime(),
				orderEsBean.getAcpTm(), "验证acpTm");
		DataUtil.verifyDateEquals(expectOrderSql.getPaidTime(),
				orderEsBean.getPaidTm(), "验证paidTm");
		DataUtil.verify(expectOrderSql.getSellerCouponCode(),
				orderEsBean.getSellerCopCod(), "验证sellerCopCod");

		DataUtil.verify(expectOrderSql.getPayableAmount(),
				orderEsBean.getUserPay(), "验证userPay");

		DataUtil.verify(expectOrderSql.getYmtCouponCode(),
				orderEsBean.getYmtCopCod(), "验证ymtCopCod");

		DataUtil.verify(expectOrderSql.getYmtCouponAmount(),
				orderEsBean.getYmtCop(), "验证ymtCop");

		DataUtil.verifyDateEquals(expectOrderSql.getReceiveTime(),
				orderEsBean.getRecvTm(), "验证recvTm");
		DataUtil.verifyDateEquals(expectOrderSql.isPreSale(),
				orderEsBean.getPreSale(), "验证preSale");

		DataUtil.verifyDateEquals(CollectionUtils.isEmpty(expectOrderSql
				.getRefunds()) ? null : true, orderEsBean.getRfded(), "验证rfded");
		DataUtil.verifyDateEquals(expectOrderSql.getRemarkLevel(),
				orderEsBean.getRmklvl(), "验证rmklvl");

		DataUtil.verifyDateEquals(expectOrderSql.isDeleted(),
				orderEsBean.getDel(), "验证del");

		BigDecimal refundCash = BigDecimal.ZERO;
		BigDecimal refundCoupon = BigDecimal.ZERO;

		if (expectOrderSql.getFund() != null) {
			refundCash = expectOrderSql.getFund().getRefundCash();
			refundCoupon = expectOrderSql.getFund().getRefundCoupon();
		}

		// 如果是直销商不需要校验
		if (expectOrderSql.getSellerId().longValue() != expectOrderSql.getGoodsOwnerId().longValue()) {

			Logger.comment("校验ES索引代理链开始");

			for (int i = 0; i < expectOrderSql.getProductProxies().size(); i++) {
				Logger.comment("校验ES索引第" + (i + 1) + "商品数据");

				ProductProxyPo expectProxyPo = expectOrderSql
						.getProductProxies().get(i);

				DataUtil.verify(
						true,
						orderEsBean
								.getPrdProxies()
								.stream()
								.anyMatch(
										productProxy -> productProxy
												.getCataId()
												.equalsIgnoreCase(
														expectProxyPo
																.getCatalogId())),
						"验证cataId");

				DataUtil.verify(
						true,
						orderEsBean
								.getPrdProxies()
								.stream()
								.anyMatch(
										productProxy -> productProxy.getTitle()
												.equalsIgnoreCase(
														expectProxyPo
																.getTitle())),
						"验证title");

				DataUtil.verify(
						true,
						orderEsBean
								.getPrdProxies()
								.stream()
								.anyMatch(
										productProxy -> productProxy
												.getSeller() == expectProxyPo
												.getSellerId()), "验证seller");

			}

			Logger.comment("校验ES索引代理链结束");
		}

		DataUtil.verify(refundCash, orderEsBean.getRfdCsh(), "验证rfdCsh");

		DataUtil.verify(refundCoupon, orderEsBean.getRfdCop(), "验证rfdCop");

		Logger.verifyEquals(expectOrderSql.getBizId(),
				orderEsBean.getBizId(), "验证bizId");
		
		DataUtil.verify(expectOrderSql.getPickupInStores(), orderEsBean.getPickupInStores(),
				"验证PickupInStores");
		DataUtil.verify(Utils.decryptAES(expectOrderSql.getUaddress()),
				orderEsBean.getAddress(), "验证Address");
		DataUtil.verify(
				expectOrderSql.getCurrency(),
				orderEsBean.getCurrency() == null ? "CNY" : orderEsBean
						.getCurrency(), "验证Currency");
		
		DataUtil.verify(expectOrderSql.getIdCardCheckResult(), orderEsBean.getIdCardChkRst(),
				"验证IdCardChkRst");
		DataUtil.verify(expectOrderSql.getCustomsClearanceStatus(), orderEsBean.getCusClearanceSt(),
				"验证CusClearanceSt");
		DataUtil.verify(expectOrderSql.getCustomsRisk(), orderEsBean.getCustomsRisk(),
				"验证CustomsRisk");
		
		if (null != expectOrderSql.getRefunds()) {
			
			// 去除失败的退款单
			List<Refund> refundListExcludeFailed = expectOrderSql
					.getRefunds()
					.stream()
					.filter(refund -> refund.getRefundStatus() == 1
							|| refund.getRefundStatus() == 10
							|| refund.getRefundStatus() == -2 ).collect(Collectors.toList());
			
			if (refundListExcludeFailed.size() > 0) {
				
				Logger.verifyEquals(true,
						orderEsBean.getHasRfd(), "验证HasRfd");
				DataUtil.verifyDateEquals(expectOrderSql
						.getRefunds()
						.get(expectOrderSql.getRefunds().size() - 1)
						.getRefundTime(),
						orderEsBean.getLstRfdTm(), "验证LstRfdTm");
			} else {
				
				DataUtil.verifyDateEquals(null,
						orderEsBean.getHasRfd(), "验证HasRfd");
				DataUtil.verifyDateEquals(null,
						orderEsBean.getLstRfdTm(), "验证LstRfdTm");
			}
		} else {
			
			DataUtil.verifyDateEquals(null,
					orderEsBean.getHasRfd(), "验证HasRfd");
			DataUtil.verifyDateEquals(null,
					orderEsBean.getLstRfdTm(), "验证LstRfdTm");
		}
		
		Logger.verifyEquals(expectOrderSql.getPlatSource(),
				orderEsBean.getPlatSrc(), "验证platSource");
		Logger.verifyEquals(expectOrderSql.getLiveOrder(),
				orderEsBean.getLiveOrder(), "验证liveOrder");
		
		if (expectOrderSql.getEarnestAmount().compareTo(BigDecimal.ZERO) == 1)
			DataUtil.verify(true, orderEsBean.getBkOrder(), "验证bookingOrder");
		else
			DataUtil.verify(false, orderEsBean.getBkOrder(), "验证bookingOrder");
		
		Logger.verifyEquals(expectOrderSql.getCrossBorderType(),
				orderEsBean.getCrsBdTy(), "验证crsBdTy");
		
		PickupStore pickupStore = expectOrderSql.getPickupStore();
		
		if (null != pickupStore) {
		
			Logger.verifyEquals(pickupStore.getPickupStatus(),
					orderEsBean.getPickStatus(), "验证pickStatus");
			DataUtil.verifyDateEquals(pickupStore.getPickupTime(),
					orderEsBean.getPickedTime(), "验证pickedTime");
			Logger.verifyEquals(pickupStore.getPickupUserName(),
					orderEsBean.getPickUserName(), "验证pickUserName");
			Logger.verifyEquals(pickupStore.getPickupUserPhone(),
					orderEsBean.getPickUserPhone(), "验证pickUserPhone");
			Logger.verifyEquals(pickupStore.getPickupStoreId(),
					orderEsBean.getPickStoreId(), "验证pickStoreId");
		}
	}

	/**
	 * 
	 * syncOrderCmd 指令同步
	 * 
	 * @param orderId
	 * @param orderSyncCmdEnum
	 *            指令枚举
	 *
	 */
	public static void syncOrderCmd(long userId, long orderId,
			TradingSyncCmdEnum orderSyncCmdEnum) {

		SyncOrderCmdCall syncOrderCmdCall = new SyncOrderCmdCall();

		Map<String, Long> orderIds = new HashMap<String, Long>();

		orderIds.put(String.valueOf(orderId),
				TradingCallService.genMainOrderId(userId));

		SyncByCommandReq syncOrderCmdBean = new SyncByCommandReq(orderIds,
				orderSyncCmdEnum.name(), userId);

		syncOrderCmdCall.setData(false, syncOrderCmdBean);

		try {
			syncOrderCmdCall.callService();
		} catch (Exception e) {

			e.printStackTrace();
		}

	}

	/**
	 * 判断砍价团订单是否需要隐藏
	 * 
	 * @param bizType
	 *            业务类型
	 * @param bizStatus
	 *            业务状态
	 * */
	private static Boolean getHidden(Integer bizType, Integer bizStatus) {
		if (bizType == null || bizType != 1 || bizStatus == null) {
			return null;
		}
		return bizStatus != 3;
	}

	/**
	 * 风控通知
	 * 
	 * @param states
	 *            Rejected pass
	 */
	public static void riskControlNotify(long orderId, String states) {

		try {

			Map<String, String> paramExt = new HashMap<String, String>();

			paramExt.put("Status", states);

			RiskControlNotifyReq riskControlNotifyReq = new RiskControlNotifyReq();
			RiskControlNotifyCall riskControlNotifyCall = new RiskControlNotifyCall();

			riskControlNotifyReq.setParamExt(paramExt);
			riskControlNotifyReq.setOrderId(orderId);

			riskControlNotifyCall.setData(false, riskControlNotifyReq);

			riskControlNotifyCall.callService();

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@SuppressWarnings("rawtypes")
	public static void gen() {
		try {

			Class cls = Order.class;

			Method[] methods = cls.getDeclaredMethods();
			Logger.info("**********************");
			for (Method m : methods) {

				String methodName = m.getName();

				if (methodName.startsWith("get") || methodName.startsWith("is")) {

					int beindex = 3;

					if (methodName.startsWith("is")) {
						beindex = 2;
					}

					String temp = String
							.format("Logger.verifyEquals(expected.%s(),actual.%s() , \"验证数据库%s\");",
									methodName, methodName,
									methodName.substring(beindex));

					System.out.println(temp);

				}

			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 
	 * @param obj
	 */
	public static void setDefaultValue(Object obj) {

		if (obj == null) {

			return;

		}

		Field[] expectFields = obj.getClass().getDeclaredFields();

		for (int i = 0; i < expectFields.length; i++) {

			Field expectField = expectFields[i];

			expectField.setAccessible(true);

			switch (expectField.getType().getName()) {

			case "java.lang.Integer":

				try {

					if (expectField.get(obj) == null) {
						expectField.set(obj, 0);
					}

				} catch (Exception e) {
					e.printStackTrace();
				}

				break;
			case "java.lang.Long":

				try {
					if (expectField.get(obj) == null) {
						expectField.set(obj, 0L);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}

				break;

			case "java.math.BigDecimal":

				try {
					if (expectField.get(obj) == null) {
						expectField.set(obj, BigDecimal.ZERO);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}

				break;

			default:
				break;
			}

		}
	}

	public static void main(String args[]) {

		// syncOrderCmd(20238699, 1103248699,
		// TradingSyncCmdEnum.LOGISTICS_CODE);
		// HunterIndex index =
		// TradingSyncService.getHunterIndexFromMongo(1869988699, 1234);
		// int i = 0;
//		verify(11485988699L, 20238699, 24635724, 0);
		verifyDGSQ(13620708699L, 20238699);

		// List<String> expected = new ArrayList<String>();
		// List<String> actual = new ArrayList<String>();
		//
		// expected.add("3503783830185");
		// expected.add("1905306142813");
		// actual.add("1905306142813");
		// actual.add("3503783830185");
		//
		// boolean test = DataUtil.verifyListStringExceptSort(expected, actual);
		// System.out.println(test);
		// Logger.info(getOrderFromMongo(1372908699).getDelivery().getBillCode());
		// Order order = TradingSyncService.getOrderFromMongo(1780028699);
		// verify(1120355087, 20325087, 512003);
		// riskControlNotify(1102168699, "pass");
		// gen();
	}
}
